<template>
  <c-back-wrap :loading="loading" go-page="经销商档案变更管理" :before-call-back="$goBackCall" :current-page="isEdit?'编辑':'新建'">
    <c-title title="客户基本信息">
      <CustomerBaseInfo
        ref="customerBaseInfo"
        v-model="customerFormData"
        :before-params="paramsJson=>{
          paramsJson.filtersRaw.push({id:'oneCategoryCode',property:'oneCategoryCode',value:'Z230',operator:'<>'})
          $codeOrName(paramsJson.filtersRaw, 'code', 'name')
          return paramsJson
        }"
        :detail="detail"
        :disabled="isEdit"
        :start-observe="startObserve"
        @change="handleCustomerChange"
      />
    </c-title>
    <c-title v-if="!!customerFormData.customerCode" title="变更内容">
      <ChangeWrap v-model="isChangeAddr" change-label="客户收货地址变更" change-before-label="变更前收货地址" change-after-label="变更后收货地址" @add="handleAdd(addressAfterTableData)">
        <ChangeAddr slot="before" :table-data="addressBeforeTableData" is-before type="view" :editable-column="['isChange']" @change="row=>setChangeAfterData('code', row, addressAfterTableData)" />
        <ChangeAddr ref="form1" slot="after" :table-data="addressAfterTableData" type="edit" :start-observe="startObserve" :editable-column="['changeType']" title="客户收货地址变更" @remove="row=>handleChangeRemove('code', row,addressBeforeTableData,addressAfterTableData)" />
      </ChangeWrap>

      <ChangeWrap v-model="isChangeContact" change-label="客户联系人变更" change-before-label="变更前客户联系人" change-after-label="变更后客户联系人" @add="handleAdd(contactsAfterTableData, 1)">
        <ChangeContacts slot="before" :table-data="contactsBeforeTableData" is-before type="view" :editable-column="['isChange']" @change="row=>setChangeAfterData('contactId', row, contactsAfterTableData)" />
        <ChangeContacts ref="form2" slot="after" :table-data="contactsAfterTableData" type="edit" :editable-column="['changeType']" title="客户联系人变更" @remove="row=>handleChangeRemove('contactId', row,contactsBeforeTableData, contactsAfterTableData)" />
      </ChangeWrap>

      <div class="shop-select">
        <QupFormContainer :column="4">
          <el-form ref="form" label-width="80px">
            <el-form-item prop="shopCode" label="选择门店">
              <c-common-search-shop
                v-model="shopCode"
                :label.sync="shopName"
                :customer-code="customerFormData.customerCode"
                :disabled="!customerFormData.customerCode"
                @change="handleSelectShopCode"
              />
            </el-form-item>
            <el-form-item prop="shopName" label="门店编码">
              {{ shopCode }}
            </el-form-item>
          </el-form>
        </QupFormContainer>
      </div>

      <template v-if="isSelectChangeShop">
        <ChangeWrap v-model="isShopBaseInfo" :show-add-btn="false" change-label="门店基本信息变更">
          <ChangeShop ref="form3" slot="after" v-model="shopChangeData" :data="shopDTOS" :shop-data="shopData" :customer-code="customerFormData.customerCode" />
        </ChangeWrap>

        <ChangeWrap v-model="isShopChangeContact" change-label="门店联系人变更" change-before-label="变更前门店联系人" change-after-label="变更后门店联系人" @add="handleAdd(shopContactsAfterTableData, 2)">
          <ChangeContacts slot="before" :table-data="shopContactsBeforeTableData" is-before type="view" :editable-column="['isChange']" @change="row=>setChangeAfterData('contactId', row, shopContactsAfterTableData)" />
          <ChangeContacts ref="form4" slot="after" :table-data="shopContactsAfterTableData" type="edit" :editable-column="['changeType']" title="门店联系人变更" @remove="row=>handleChangeRemove('contactId', row,shopContactsBeforeTableData,shopContactsAfterTableData)" />
        </ChangeWrap>
      </template>

    </c-title>

    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleSave">保存草稿</c-button>
      <c-button type="primary" @click="handleSubmit">提交</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { archiveDetail, archiveSave, archiveSubmit, getShopData } from '@/api/channelTask2/archiveChange'
import { customerAddress, contactByCustomer, contactByShop } from '@/api/channelTask2/change'

import CustomerBaseInfo from '../../components/CustomerBaseInfo'
import ChangeAddr from './ChangeAddr'
import ChangeContacts from './ChangeContacts'
import ChangeShop from './ChangeShop'
import ChangeWrap from './ChangeWrap'

export default {
  name: 'AddEdit',
  components: {
    ChangeAddr,
    ChangeContacts,
    ChangeShop,
    CustomerBaseInfo,
    ChangeWrap
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detail: {},
      loading: false,
      customerFormData: {},
      // 收货地址变更
      isChangeAddr: 0,
      // 收货地址
      addressBeforeTableData: [],
      addressAfterTableData: [],
      // 客户联系人变更
      isChangeContact: 0,
      contactsBeforeTableData: [],
      contactsAfterTableData: [],
      // 门店基本信息
      isShopBaseInfo: 0,
      shopChangeData: [],
      shopData: {},
      shopCode: '',
      shopName: '',
      // 门店联系人变更
      isShopChangeContact: 0,
      shopContactsBeforeTableData: [],
      shopContactsAfterTableData: [],

      formData: {},
      formRules: {},
      startObserve: false
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },

    // 门店
    shopDTOS() {
      return this.detail.shopDTOS || []
    },
    // 是否选择变更门店
    isSelectChangeShop() {
      return Object.keys(this.shopData || {}).length > 0 && this.shopData.code !== '' && this.shopData.code !== undefined
    }
  },
  created() {
    if (this.id) {
      this.getDetailData().then(() => {
        setTimeout(() => {
          this.startObserve = true
        })
      })
    } else {
      this.startObserve = true
    }
  },
  methods: {
    getDetailData() {
      this.loading = true
      return archiveDetail(this.id).then(async res => {
        this.detail = res.data
        this.loading = false
        await this.initData()
      }).catch(() => {
        this.loading = false
      })
    },
    // 编辑初始化数据
    async initData() {
      const d = this.$deepClone(this.detail)
      // 处理数据
      const handle = (before, after, key) => {
        before.forEach(e => {
          if (after.some(ee => ee[key] === e[key])) {
            e.isChange = 1
          }
          e.raw = this.$deepClone(e)
        })
        after.forEach(e => {
          const tmp = before.find(ee => ee[key] === e[key])
          if (tmp) {
            e.raw = this.$deepClone(tmp)
            if (e.raw.raw) {
              delete e.raw.raw
            }
          }
        })
      }
      // 设置是否变更
      const isChange = (d, key) => {
        this[key] = d.length > 0 ? 1 : 0
      }
      // 收货地址
      const addressBeforeTableData = d.addressDTOS.filter(e => [1, '1'].includes(e.isBefore))
      const addressAfterTableData = d.addressDTOS.filter(e => ![1, '1'].includes(e.isBefore))
      handle(addressBeforeTableData, addressAfterTableData, 'code')
      isChange(addressAfterTableData, 'isChangeAddr')
      this.addressAfterTableData = addressAfterTableData
      this.addressBeforeTableData = addressBeforeTableData
      // 客户联系人
      const contactsBeforeTableData = d.contactDTOS.filter(e => [1, '1'].includes(e.isBefore) && ([1, '1'].includes(e.contactScope) || !!e.customerCode))
      const contactsAfterTableData = d.contactDTOS.filter(e => ![1, '1'].includes(e.isBefore) && ([1, '1'].includes(e.contactScope) || !!e.customerCode))
      handle(contactsBeforeTableData, contactsAfterTableData, 'contactId')
      isChange(contactsAfterTableData, 'isChangeContact')
      this.contactsBeforeTableData = contactsBeforeTableData
      this.contactsAfterTableData = contactsAfterTableData
      // 门店联系人
      const shopContactsBeforeTableData = d.contactDTOS.filter(e => [1, '1'].includes(e.isBefore) && ([3, '3'].includes(e.contactScope) || !!e.shopCode))
      const shopContactsAfterTableData = d.contactDTOS.filter(e => ![1, '1'].includes(e.isBefore) && ([3, '3'].includes(e.contactScope) || !!e.shopCode))
      handle(shopContactsBeforeTableData, shopContactsAfterTableData, 'contactId')
      isChange(shopContactsAfterTableData, 'isShopChangeContact')
      this.shopContactsBeforeTableData = shopContactsBeforeTableData
      this.shopContactsAfterTableData = shopContactsAfterTableData
      // 门店
      if (d.shopDTOS.length > 0) {
        const t = d.shopDTOS[0]
        this.shopData = await getShopData(d.customerCode, t.code)
        this.shopCode = this.shopData.code
        this.shopName = this.shopData.name
      } else if (d.contactDTOS.length > 0) {
        const t = d.contactDTOS[0]
        this.shopData = await getShopData(d.customerCode, t.shopCode)
        this.shopCode = this.shopData.code
        this.shopName = this.shopData.name
      }
      // 基础信息
      this.shopChangeData = d.shopDTOS
      this.isShopBaseInfo = this.shopChangeData.length > 0 ? 1 : 0
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    // 客户发生变化
    handleCustomerChange(customerCode) {
      this.isChangeAddr = 0
      this.isChangeContact = 0
      // 客户收货地址
      this.addressBeforeTableData = []
      this.addressAfterTableData = []
      // 客户联系人
      this.contactsBeforeTableData = []
      this.contactsAfterTableData = []
      // 门店联系人
      this.shopContactsBeforeTableData = []
      this.shopContactsAfterTableData = []
      this.handleSelectShopCode({})
      if (!customerCode) {
        return
      }
      const p = []
      p.push(customerAddress(customerCode).then(res => {
        this.addressBeforeTableData = res.data.map(e => {
          e.raw = this.$deepClone(e)
          return e
        })
      }))
      p.push(contactByCustomer(customerCode).then(res => {
        this.contactsBeforeTableData = res.data.map(e => {
          e.raw = this.$deepClone(e)
          e.contactScope = 1
          return e
        })
      }))
      return Promise.all(p)
    },
    // 新增
    handleAdd(data, type) {
      const t = {
        changeType: 'B',
        isChange: 1,
        isBefore: 0
      }
      if (type === 1) {
        t.customerCode = this.customerFormData.customerCode
        t.contactScope = 1
      } else if (type === 2) {
        t.shopCode = this.shopData.code
        t.contactScope = 3
      }
      data.push(t)
    },
    // 删除
    handleChangeRemove(key, row, beforeData, afterData) {
      const index = afterData.findIndex(e => e === row)
      afterData.splice(index, 1)
      if (row.changeType !== 'B') {
        const item = beforeData.find(e => e[key] === row[key])
        if (item) {
          this.$set(item, 'isChange', 0)
        }
      }
    },
    // 门店变更
    handleSelectShopCode(shop) {
      this.shopData = shop

      this.isShopBaseInfo = 0
      this.shopChangeData = []

      this.shopCode = shop.code
      this.shopName = shop.name
      // 门店联系人变更
      this.isShopChangeContact = 0
      this.shopContactsBeforeTableData = []
      this.shopContactsAfterTableData = []

      if (!shop.code) {
        return
      }
      return contactByShop(shop.code).then(res => {
        this.shopContactsBeforeTableData = res.data.map(e => {
          e.raw = this.$deepClone(e)
          e.contactScope = 3
          return e
        })
      })
    },
    // 提交验证数据
    async validate() {
      await this.$refs.customerBaseInfo.validate()
      const isTrue = v => {
        return [1, '1'].includes(v)
      }
      const isKeys = 'isChangeAddr:form1 isChangeContact:form2 isShopBaseInfo:form3 isShopChangeContact:form4'.split(' ')
      for (let k of isKeys) {
        k = k.split(':')
        if (isTrue(this[k[0]])) {
          await this.$refs[k[1]].validate()
        }
      }
      if ('isChangeAddr isChangeContact isShopBaseInfo isShopChangeContact'.split(' ').every(k => !this[k])) {
        const msg = '没有模块发生变更!'
        this.$message.warning(msg)
        return Promise.reject(msg)
      }
      return Promise.resolve(true)
    },
    // 处理变更数据
    handleData(data) {
      const tmp = this.$deepClone(data)
      const ignoreKeys = 'raw changeType isBefore'.split(' ')
      tmp.forEach(e => {
        const raw = e.raw
        delete e.raw
        if (e.changeType === 'C') {
          Object.keys(e).forEach(k => {
            if (ignoreKeys.includes(k)) return
            e[k] = raw[k]
          })
        }
      })
      return tmp
    },
    getPostData(isSubmit) {
      const data = {}
      if (this.isEdit) {
        Object.assign(data, this.detail)
      }
      Object.assign(data, this.customerFormData)
      if (isSubmit) {
        // 收货地址
        const addressDTOS = []
        if (this.isChangeAddr) {
          addressDTOS.push(...this.handleData(this.addressBeforeTableData))
          addressDTOS.push(...this.handleData(this.addressAfterTableData))
        }
        data.addressDTOS = addressDTOS

        // 联系人
        const contactDTOS = []
        if (this.isChangeContact) {
          contactDTOS.push(...this.handleData(this.contactsBeforeTableData))
          contactDTOS.push(...this.handleData(this.contactsAfterTableData))
        }
        if (this.isShopChangeContact) {
          contactDTOS.push(...this.handleData(this.shopContactsBeforeTableData))
          contactDTOS.push(...this.handleData(this.shopContactsAfterTableData))
        }
        data.contactDTOS = contactDTOS
        // 门店
        data.shopDTOS = (this.isShopBaseInfo ? this.shopChangeData : []).filter(e => [1, '1'].includes(e.isChange))
      } else {
        // 收货地址
        data.addressDTOS = this.isChangeAddr ? this.handleData(this.addressAfterTableData) : []
        // 联系人
        data.contactDTOS = [
          ...(this.isChangeContact ? this.handleData(this.contactsAfterTableData) : []),
          ...(this.isShopChangeContact ? this.handleData(this.shopContactsAfterTableData) : [])
        ]
        // 门店
        data.shopDTOS = (this.isShopBaseInfo ? this.shopChangeData : []).filter(e => [1, '1'].includes(e.isChange))
      }
      data.type = 'H'
      return data
    },
    handleSave() {
      return archiveSave(this.getPostData()).then(res => {
        this.$message.success('操作成功!')
        this.$pageStack.pop('opCondition')
      })
    },
    handleSubmit() {
      return this.validate().then(() => {
        return archiveSubmit(this.getPostData(true)).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    },
    setChangeAfterData(property, row, data) {
      const i = data.findIndex(e => e[property] === row[property])
      if ([0, '0'].includes(row.isChange) && i >= 0) {
        data.splice(i, 1)
      } else if (i < 0) {
        row.isBefore = 0
        data.push(row)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.shop-select{
  padding-top: 20px;
}
</style>
